package com.appkubes.mall.restful.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfiguration {

    /**
     * 订单状态，路由
     */
    @Value("${mq.order.exchange}")
    private String apiCountExchange;

    @Value("${mq.order.queue}")
    private String apiCountQueue;

    @Value("${mq.order.routingkey}")
    private String routingkey;

    /**
     * 消费者数量，默认50
     */
    public static final int DEFAULT_CONCURRENT = 50;

    /**
     * 每个消费者获取最大投递数量 默认1
     */
    public static final int DEFAULT_PREFETCH_COUNT = 1;

    @Bean
    public DirectExchange apiCountExchange() {
        return new DirectExchange(apiCountExchange);
    }

    @Bean
    public Binding apiCountRoutingKeyBind() {
        return BindingBuilder.bind(apiCountQueue()).to(apiCountExchange()).with(routingkey);
    }

    @Bean
    public Queue apiCountQueue() {
        // 默认是durable=true的
        return new Queue(apiCountQueue);
    }

    @Bean(name="connectionFactory")
    public ConnectionFactory connectionFactory(
            @Value("${spring.rabbitmq.host}") String host,
            @Value("${spring.rabbitmq.port}") int port,
            @Value("${spring.rabbitmq.username}") String username,
            @Value("${spring.rabbitmq.password}") String password,
            @Value("${spring.rabbitmq.vhost}") String vhost
    ){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(vhost);
        return connectionFactory;
    }

    @Bean("pointTaskContainerFactory")
    public SimpleRabbitListenerContainerFactory pointTaskContainerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        //消费者数量，默认50
        factory.setPrefetchCount(DEFAULT_CONCURRENT);
        //每个消费者获取最大投递数量 默认1
        factory.setConcurrentConsumers(DEFAULT_PREFETCH_COUNT);
        configurer.configure(factory, connectionFactory);
        return factory;
    }

}
